package com.imooc.mq.activemq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.jms.*;


@Service
@Slf4j
public class ActivemqSendMessage  {

    @Autowired
    private JmsTemplate jmsTemplate;
    @Resource(name="activeQueue") //指向队列
    private Destination destination;


    @Transactional(value = "jtaTransactionManager",rollbackFor = Exception.class)
    public void sendActiveQueue(String messageStr){
        final String str=messageStr;
        //指定发送到activeQueue的一个消息
        jmsTemplate.send(destination,new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                TextMessage msg = session.createTextMessage();
                msg.setText(str);
                log.info("activemq消息发送："+str);
                //测试此处发生异常，消息会不会发送？测试结果：在返回前发送异常，则消息不会被发送
                if("senderror".equals(str)){
                    throw new RuntimeException("我是 发送 error!");
                }
                return msg;
            }
        });
        //测试此处发生异常，消息会不会发送？测试结果：消息会被发送
        if("senddown".equals(str)){
            throw new RuntimeException("我是 发送结束 error!");
        }

    }

//    public void receive(){
//        Message msg = jmsTemplate.receive();
//        TextMessage tm = (TextMessage)msg;
//        log.info("activemq消息发送："+messageStr);
//        log.info(msg);
//        System.out.println("非监听------------------非监听");
//        System.out.println(msg);
//    }

}
